import { Rule } from '/@/components/Form';
import { ComponentTypeEnum } from '../types/index';
import { verify } from '/@/utils/validator';
import { commonVerifyDataUniqueApi } from '/@/api/config-center/model-design';

// type ReturnType = ((renderCallbackParams: RenderCallbackParams) => Rule[]) | undefined;

function getRules(schema: Indexable): Rule[] | undefined {
  const { componentType, rules, isUnique, field, modelId, componentProps } = schema;
  const reRules: Indexable[] = rules || [];
  reRules.forEach((rule) => {
    if (rule.pattern) {
      const { value, label } = verify[rule.pattern] || {};
      rule.pattern = value;
      //  如果没有校验信息这用正则配置的校验信息
      if (!rule.message) {
        rule.message = label;
      }
    }
  });

  // isUnique 0 唯一， 1 是不唯一
  if (isUnique === 0) {
    const verify: Rule = {
      trigger: 'blur',
      validator(_, value) {
        return new Promise((resolve, reject) => {
          commonVerifyDataUniqueApi({
            modelId,
            field,
            content: value,
            oldContent: componentProps.defaultValue,
          })
            .then((data) => {
              if (data) return resolve();
              return reject('该数据已存在，请勿重复');
            })
            .catch((err) => reject(err.message || '验证失败'));
        });
      },
    };
    reRules.push(verify);
  }
  switch (componentType) {
    case ComponentTypeEnum.SubTable:
      return setSubTableRules(schema, reRules);

    default:
      if (reRules) return reRules;
  }
}

function setSubTableRules(schema: Indexable, rules): Rule[] {
  return [verify.requireSubTableArrayItem({ schema }), ...rules];
}

export default getRules;
